package com.hmdp.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
@Slf4j
public class RedisIdWorker {

    private static final long begin_time = 1734042046;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 生成全局唯一id
    public long nextId(String keyPrefix){
        if (keyPrefix == null) {
            throw new RuntimeException("keyPrefix is null");
        }
        // 以秒为时间戳 获取当前秒数为时间戳
        LocalDateTime now = LocalDateTime.now();
        long time = now.toEpochSecond(ZoneOffset.UTC) - begin_time;
        // 获取redis自增 并转换为序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        return time << 32 | increment;
    }

}
